/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.dlc.shop.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.bean.model.PlatformAddr;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.dao.PlatformAddrMapper;
import com.dlc.shop.service.PlatformAddrService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 平台地址库，用于国内收货地址和国外的发货地址
 * @author liyong
 */
@Service
@AllArgsConstructor
public class PlatformAddrServiceImpl extends ServiceImpl<PlatformAddrMapper, PlatformAddr>
        implements PlatformAddrService {

    private final PlatformAddrMapper platformAddrMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addPlatformAddr(PlatformAddr platformAddr) {
        if (Objects.equals(platformAddr.getDefaultAddr(), 1)) {
            platformAddrMapper.cancelDefaultAddr(platformAddr.getShopId());
        }
        platformAddrMapper.insert(platformAddr);
        return  platformAddr.getAddrId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePlatformAddr(Long shopId, PlatformAddr platformAddr) {
        if (Objects.equals(platformAddr.getDefaultAddr(), 1)) {
            platformAddrMapper.cancelDefaultAddr(shopId);
        }
        platformAddrMapper.updateById(platformAddr);
    }

    @Override
    public List<PlatformAddr> queryList() {
        List<PlatformAddr> list = platformAddrMapper.selectList(new LambdaQueryWrapper<PlatformAddr>()
                .eq(PlatformAddr::getShopId, Constant.PLATFORM_SHOP_ID)
                .eq(PlatformAddr::getStatus, 1)
                .orderByDesc(PlatformAddr::getUpdateTime));
        if (CollUtil.isNotEmpty(list)) {
            for (PlatformAddr record : list) {
                if (Objects.nonNull(record.getReceiverMobile())) {
                    record.setReceiverMobile(PhoneUtil.hideBetween(record.getReceiverMobile()).toString());
                }
                String tel = record.getReceiverTelephone();
                if (StrUtil.isNotBlank(tel)) {
                    String after = !tel.contains("-") ? tel : tel.split("-")[1];
                    String afterHide = PhoneUtil.hideBetween(after).toString();
                    String before = !tel.contains("-") ? "" : tel.split("-")[0] + "-";
                    record.setReceiverTelephone(before + afterHide);
                }
            }
        }
        return list;
    }


}
